package com.lez.coroutine02

import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.runBlocking
import org.junit.Test

class Coroutine03 {

    suspend fun performRequest(request: Int) : String{
        delay(1000)
        return "request $request"
    }
    @Test
    fun `test transform flow operator`() = runBlocking {
        (1..5).asFlow()  //asFlow()流构建器
            //.map { request -> performRequest(request) }  //map函数：可遍历数组中的元素，做一定操作之后返回一个列表
            .transform { request ->    //利用transform转换操作符可以发射两个值
                emit("making request $request")
                emit(performRequest(request))
            }
            .collect { value -> println(value) }
    }

    //限长操作符 take()
    @Test
    fun `test flow limite length`() = runBlocking{
        (1..5).asFlow()
            .take(3)//take()流构建器
            .collect { value -> println(value) }
    }
    //末端操作符
    @Test
    fun `test terminal operator`() = runBlocking {
        val sum = (1..5).asFlow()
            .map { it * it }
            .reduce{a,b ->   //reduce 计算累加和
                a+b
            }
        println(sum)
    }
}